package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.atguigu.dao.TravelGroupDao;
import com.atguigu.entity.PageResult;
import com.atguigu.pojo.TravelGroup;
import com.atguigu.service.TravelGroupService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {
    @Autowired
    TravelGroupDao travelGroupDao;

    @Override
    public void add(TravelGroup travelGroup, Integer[] travelItemIds) {
    //1.新增跟团游，想t_travelgroup中添加数据，新增后返回新的id
        travelGroupDao.add(travelGroup);
        Integer travelGroupId = travelGroup.getId();
        //保存跟团游和中间表数据
        setTravelGroupAndTravelItem(travelGroupId,travelItemIds);
    }



    private void setTravelGroupAndTravelItem(Integer travelGroupId, Integer[] travelItemIds) {
        if (travelItemIds!=null&&travelItemIds.length>0) {
            for (Integer travelItemId : travelItemIds) {
                //涉及多个数据的保存用集合
                Map<String,Integer> map = new HashMap<>();
                map.put("travelGroupId", travelGroupId);
                map.put("travelItemId", travelItemId);
                travelGroupDao.setTravelGroupAndTravelItem(map);
            }
        }
    }
    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page page=travelGroupDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public TravelGroup get(Integer id) {
        return travelGroupDao.get(id);
    }

    @Override
    public List<Integer> getTravelItemIds(Integer travelGroupId) {
        return travelGroupDao.getTravelItemIds(travelGroupId);
    }

    @Override
    public void edit(Integer[] travelItemIds, TravelGroup travelGroup) {
        //1.修改跟团游的基本信息
        travelGroupDao.edit(travelGroup);
        /*2.修改跟团游和自由行的中间表（先删除,再删除）
        * 之前的数据删除
        * 再新增页面选中的数据
        * */
        //删除之前的数据
        travelGroupDao.deleteTravelGroupAndTravelItemByTravelGroupId(travelGroup.getId());
        //再新增页面选中的数据
        setTravelGroupAndTravelItem(travelGroup.getId(),travelItemIds);



    }

    @Override
    public List<TravelGroup> findAll() {
        return travelGroupDao.findAll();
    }

  /*  @Override
    public void delete(Integer id) {
        travelGroupDao.delete(id);
    }
*/

}

